package com.xx.ems.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.xx.ems.dao.UsersCRUDDao;
import com.xx.ems.model.Departments;
import com.xx.ems.model.Users;
import com.xx.ems.system.BaseDao;

@Repository(value="usersCRUDDao")
@Transactional
public class UsersCRUDDaoImpl extends BaseDao implements UsersCRUDDao {
	@Override
	public void addUser(Users users) {
		Departments department = (Departments) getCurrentSession().createQuery("from Departments de where de.dname = '" + users.getDepartment().getDname() + "'").uniqueResult();
		users.setDepartment(department);
		getCurrentSession().save(users);
	}

	@Override
	public void updateUser(Users users) {
		Users olduser = (Users) getCurrentSession().get(Users.class, users.getUid());
		BeanUtils.copyProperties(olduser, users);
		getCurrentSession().update(olduser);
	}

	@Override
	public void deleteUser(int id) {
		getCurrentSession().createQuery("delete from Users user where user.id = "+id).executeUpdate();
	}
	
	@Override
	public String isExistUser(String account) {
		Users user = (Users) getCurrentSession().createQuery("from Users user where user.account = '"+account+"'").uniqueResult();
		if (user != null) {
			return user.getUsername();
		}else {
			return null;
		}
	}

	@Override
	public Users getSpecificUser(String account) {
		Users user = (Users) getCurrentSession().createQuery("from Users user where user.account = '"+account+"'").uniqueResult();
		return user;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getUsersList(int pageNow, int maxCount) {
		/**
		 * 获取用户列表
		 */
		String hql = "from Users user order by user.uid asc";
		List<Users> userList = getPagingList(pageNow, maxCount, hql);
		List<Object> list = new ArrayList<Object>();
		for (Users user : userList) {
			list.add(user.toHashMap());
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		map.put("totalpage", getTotalpage());
		return map;
	}
}